package com.yhy.job.utils;

import com.yhy.common.exception.BusinessException;
import com.yhy.job.vo.mng.QuartzJobMngVO;
import com.yhy.job.vo.QuartzJobVO;
import org.quartz.*;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.Date;

import static org.quartz.TriggerBuilder.newTrigger;

/*
 *
 *  * *
 *  *  * <br>
 *  *  * <b>功能：</b><br>
 *  *  * <b>作者：</b>yanghuiyaun<br>
 *  *  * <b>日期：</b> 19-8-16 下午3:17 <br>
 *  *  * <b>版权所有：<b>版权所有(C) 2019<br>
 *  *
 *
 */
@Component
public class QuartzJobManage {

    private static Logger logger = LoggerFactory.getLogger(QuartzJobManage.class);

    //加入Qulifier注解，通过名称注入bean
    @Autowired
    @Qualifier("scheduler")
    private Scheduler scheduler;

    public void addJob(QuartzJobMngVO quartzJob) {
        try {
            // 构建job信息
            JobDetail jobDetail = JobBuilder.newJob(ExecutionJob.class).
                    withIdentity(quartzJob.getId()).build();

            //通过触发器名和cron 表达式创建 Trigger
            Trigger cronTrigger = newTrigger()
                    .withIdentity(quartzJob.getId())
                    .startNow()
                    .withSchedule(CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression()))
                    .build();
            quartzJob.setRunning(false);
            cronTrigger.getJobDataMap().put(QuartzJobVO.JOB_KEY, quartzJob);

            //重置启动时间
            ((CronTriggerImpl)cronTrigger).setStartTime(new Date());

            //执行定时任务
            scheduler.scheduleJob(jobDetail,cronTrigger);

            // 暂停任务
            if (quartzJob.getPause()) {
                pauseJob(quartzJob);
            }
        } catch (Exception e){
            logger.error("创建定时任务失败", e);
            throw new BusinessException("创建定时任务失败");
        }
    }

    /**
     * 更新job cron表达式
     * @param quartzJob
     * @throws SchedulerException
     */
    public void updateJob(QuartzJobMngVO quartzJob) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(quartzJob.getId());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 如果不存在则创建一个定时任务
            if(trigger == null){
                addJob(quartzJob);
                trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            }
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression());
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            //重置启动时间
            ((CronTriggerImpl)trigger).setStartTime(new Date());
            trigger.getJobDataMap().put(QuartzJobVO.JOB_KEY,quartzJob);

            scheduler.rescheduleJob(triggerKey, trigger);
            // 暂停任务
            if (quartzJob.getPause()) {
                pauseJob(quartzJob);
            }
        } catch (Exception e){
            logger.error("更新定时任务失败", e);
            throw new BusinessException("更新定时任务失败");
        }

    }

    /**
     * 删除一个job
     * @param quartzJob
     * @throws SchedulerException
     */
    public void deleteJob(QuartzJobMngVO quartzJob){
        try {
            JobKey jobKey = JobKey.jobKey(quartzJob.getId());
            scheduler.deleteJob(jobKey);
        } catch (Exception e){
            logger.error("删除定时任务失败", e);
            throw new BusinessException("删除定时任务失败");
        }
    }

    /**
     * 恢复一个job
     * @param quartzJob
     * @throws SchedulerException
     */
    public void resumeJob(QuartzJobMngVO quartzJob){
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(quartzJob.getId());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 如果不存在则创建一个定时任务
            if(trigger == null)
                addJob(quartzJob);
            JobKey jobKey = JobKey.jobKey(quartzJob.getId());
            scheduler.resumeJob(jobKey);
        } catch (Exception e){
            logger.error("恢复定时任务失败", e);
            throw new BusinessException("恢复定时任务失败");
        }
    }

    /**
     * 立即执行job
     * @param quartzJob
     * @throws SchedulerException
     */
    public void runJobNow(QuartzJobMngVO quartzJob){
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(quartzJob.getId());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 如果不存在则创建一个定时任务
            if(trigger == null)
                addJob(quartzJob);
            JobDataMap dataMap = new JobDataMap();
            dataMap.put(QuartzJobVO.JOB_KEY, quartzJob);
            JobKey jobKey = JobKey.jobKey(quartzJob.getId());
            scheduler.triggerJob(jobKey,dataMap);
        } catch (Exception e){
            logger.error("定时任务执行失败", e);
            throw new BusinessException("定时任务执行失败");
        }
    }

    /**
     * 暂停一个job
     * @param quartzJob
     * @throws SchedulerException
     */
    public void pauseJob(QuartzJobMngVO quartzJob){
        try {
            JobKey jobKey = JobKey.jobKey(quartzJob.getId());
            scheduler.pauseJob(jobKey);
        } catch (Exception e){
            logger.error("定时任务暂停失败", e);
            throw new BusinessException("定时任务暂停失败");
        }
    }
}
